<template>
    <div class="payment">
        <el-steps :active="activeIndex" finish-status="success" align-center simple>
            <el-step title="确认订单"></el-step>
            <el-step title="选择支付方式"></el-step>
            <el-step title="完成支付"></el-step>
        </el-steps>
        <div class="step-content">
            <div v-show="activeIndex === 0">
                <h3 style="text-align: left">确认收货地址 <a class="addAddress"
                                                             @click="dialogVisible = true">新增地址</a></h3>
                <el-dialog :visible.sync="dialogVisible" title="新增地址" width="40%" :close-on-click-modal="false"
                           @close-dialog="closeDia()" @close=getAddress()>
                    <addresses></addresses>
                </el-dialog>
                <hr style="margin-top: 5px;margin-bottom: 20px">
                <el-radio-group v-model="selected" class="vertical-radio-group">
                    <el-radio v-for="(address, index) in addresses" :key="index" size="large"
                              :label="address.serialNumber"
                              style="margin: 10px">
                        <strong>{{ address.consignee }}</strong>
                        {{ address.consigneeProvince }}
                        {{ address.consigneeCity }}
                        {{ address.consigneeDistrict }}
                        {{ address.consigneeDetialedAddress }}
                        {{ address.consigneePhone }}
                    </el-radio>
                </el-radio-group>

                <h3 style="text-align: left;margin-top: 30px">确认订单信息</h3>
                <hr style="margin-top: 5px;margin-bottom: 20px">
                <el-table :data="tableData" stripe
                          :summary-method="getSummaries"
                          show-summary
                          style="width: 100%">
                    <el-table-column
                            prop="itemName"
                            label="商品名称"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="itemId"
                            label="类别"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="version"
                            label="版本">
                    </el-table-column>
                    <el-table-column
                            prop="color"
                            label="颜色">
                    </el-table-column>
                    <el-table-column
                            prop="listprice"
                            label="单价">
                    </el-table-column>
                    <el-table-column
                            prop="count"
                            label="数量">
                    </el-table-column>
                    <el-table-column
                            prop="totalprice"
                            label="小计">
                    </el-table-column>
                </el-table>
                <div>
                    <a class="pay" @click="pay">提交订单</a>
                </div>
            </div>
            <div v-show="activeIndex === 1">
                <h3>选择支付方式</h3>
                <el-divider></el-divider>
                <el-radio-group v-model="paymentMethod">
                    <el-radio label="alipay">支付宝支付</el-radio>
                    <el-radio label="wechatpay">微信支付</el-radio>
                </el-radio-group>
                <el-button type="primary" size="medium" @click="confirmPayment">确认支付</el-button>
                <el-button type="text" size="medium" @click="prevStep">返回</el-button>
            </div>
            <div v-show="activeIndex === 2">
                <h3>完成支付</h3>
                <el-divider></el-divider>
                <p>您已成功支付 {{ orderData.totalPrice }} 元，订单号为：{{ orderId }}</p>
                <el-button type="primary" size="medium" @click="gotoOrder">查看订单</el-button>
            </div>
        </div>


    </div>
</template>

<script>
import addresses from "@/components/cart/addresses.vue";
import axios from "axios";

export default {
    mounted() {
        this.item()
        this.getAddress()
    },
    components: {
        addresses
    },
    data() {
        return {
            activeIndex: 0,
            orderData: {
                name: '商品1',
                price: 50,
                quantity: 1,
                totalPrice: 50
            },
            paymentMethod: '',
            orderId: '',
            selected: '',
            addresses: [
                //     {
                //   serialNumber:'',
                //   consignee: '选项1',
                //   consigneePhone: '1',
                //   consigneeProvince:'',
                //   consigneeCity:'',
                //   consigneeDistrict:'',
                //   consigneeDetialedAddress:''
                // },
                {label: '选项2', value: '2'},
                {label: '选项3', value: '3'}
            ],
            dialogVisible: false,

            tableData: [{
                itemName: '',
                itemId: '',
                listprice: '',
                color: '',
                version: '',
                count: '',
                totalprice: ''
            }]

        }
    },
    methods: {
        closeDia() {
            console.log('收到子组件的emit')
            this.dialogVisible = true
        },
        nextStep() {
            this.activeIndex++
        },
        prevStep() {
            this.activeIndex--
        },
        confirmPayment() {
            // 向后端发起支付请求并获得订单号
            // 成功后将orderId设置为后端返回的订单号
            this.orderId = '123456'
            this.activeIndex++
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总价';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] += ' 元';
                } else {
                    sums[index] = 'N/A';
                }
            });

            for (let i = 0; i < sums.length; i++) {
                if (i > 0 && i < sums.length - 1) sums[i] = ''
            }
            return sums;
        },
        getAddress() {
            axios({
                method: 'get',
                url: '/addresses',
                headers: {
                    "token": window.sessionStorage.getItem("token")
                }
            }).then(res => {
                this.addresses = res.data.data
                for (let i = 0; i < this.addresses.length; i++) {
                    if (this.addresses[i].isDefault === '1') {
                        this.selected = this.addresses[i].serialNumber
                        break;
                    }
                }
            })
        },
        item() {
            if (!this.$route.params.isGouWuChe) {
                this.tableData[0].itemName = this.$route.params.itemName
                this.tableData[0].itemId = this.$route.params.itemId
                this.tableData[0].listprice = this.$route.params.listprice
                this.tableData[0].color = this.$route.params.color
                this.tableData[0].version = this.$route.params.version
                this.tableData[0].count = this.$route.params.count
                this.tableData[0].totalprice = this.tableData[0].count * this.tableData[0].listprice
                console.log(this.tableData)
            } else {
                this.tableData = this.$route.params.cartData
            }
        },
        pay() {
            if (this.tableData.length !== 0) {
                for (let i = 0; i < this.tableData.length; i++) {
                    axios({
                        url: '/orders',
                        method: 'post',
                        data: {
                            orderId: "",
                            addressId: this.addresses[this.selected - 1].id,
                            itemId: this.tableData[i].itemId,
                            count: this.tableData[i].count
                        },
                        headers: {
                            "token": window.sessionStorage.getItem("token")
                        }
                    }).then(res => {
                        console.log(res)

                    })
                }
                this.$message.success('成功生成订单')
                axios({

                    url: '/carts/items',
                    method: 'DELETE',
                    headers: {
                        "token": window.sessionStorage.getItem("token")
                    }
                }).then(res => {
                    this.$router.push({
                        name: 'MainPage'
                    })
                })
            }
        }


    }
}
</script>

<style scoped>
.payment {
    width: 70%;
    margin: 20px auto
}

.addAddress {
    float: right;
    font-size: 14px;
    font-weight: 500;
    color: #3366CC;
}

.addAddress:hover {
    cursor: pointer;
    color: #ff5500;
}

.vertical-radio-group {
    display: flex;
    flex-direction: column;

}

.step-content {
    margin-top: 20px;
}

.pay {
    padding: 3px;
    margin-top: 10px;
    float: right;
    background-color: #ff5000;
    display: inline-block;
    width: 182px;
    height: 39px;
    position: relative;
    vertical-align: middle;
    line-height: 39px;
    cursor: pointer;
    text-align: center;
    font-size: 14px;
    font-weight: 700;
    color: #fff;
}

.pay :hover {
    cursor: pointer;
    background: #dd2727;
}

</style>